<template>
  <!-- ASN单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="950px"
      draggable
      @close="closeDialog"
      :append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              v-show="!props.isReadonly || !formData.id"
              type="success"
              plain
              @click="handleAdd"
            >
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="部门"
                props="departmentName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.departmentName'"
                    label-width="0"
                  >
                    <SelectOriganizationDangerGrant
                      v-if="!props.isReadonly"
                      @change="(ids:string) => getSelectIds(ids, row)"
                      @change-data="(datas) => getSelectDatas(datas, row)"
                      :isCheckStrictly="true"
                      :isMultiple="false"
                      :disabled="false"
                      :data="dataObject('领用部门')"
                      :selectData="row.departmentName"
                    />
                    <span v-else>{{ row.departmentName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="姓名"
                props="teamUserName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.teamUserName'"
                    label-width="0"
                  >
                    <el-select
                      style="width: 100%"
                      v-if="!props.isReadonly"
                      v-model="row.teamUserName"
                      placeholder="请选择姓名"
                      clearable
                      @change="(e) => changePerson(e, '领用人', row)"
                    >
                      <el-option
                        v-for="item in personList"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>{{ row.teamUserName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="是否小组负责人"
                props="isLeader"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.isLeader'"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.isLeader"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList('YesNo')"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>
                      {{
                        row.isLeader ? useDictionary("YesNo", row.isLeader) : ""
                      }}
                    </span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="角色" props="roleName" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.roleName'"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.roleName"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'TeamRole'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>
                      {{
                        row.roleName
                          ? useDictionary("TeamRole", row.roleName)
                          : ""
                      }}
                    </span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="联系电话"
                props="telNumber"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.telNumber'"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.telNumber"
                      placeholder="请输入联系电话"
                      clearable
                    />
                    <span v-else>{{ row.telNumber }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="150"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    @click="handleone(scope.$index)"
                  >
                    保存
                  </el-button>
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="success"
            :loading="loading"
            @click="handleSubmit()"
            >提 交</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMSRMASNADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let plants = ref([]);
let materials = ref([]);
let partners = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";

    // 确保 newVal 存在并且有一个 id 属性
    if (newVal?.id) {
      // 确保 details 是一个数组并且至少有一个元素
      const details =
        Array.isArray(newVal.details) && newVal.details.length > 0
          ? newVal.details[0]
          : {};

      const {
        id,
        orderNo,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        asnCode,
        partnerId,
        partnerCode,
        partnerName,
        asnDate,
        arriveDate,
        modeTransport,
        trackingNumber,
        storageLocationId,
        storageLocationCode,
        storageLocationName,
        carrier,
        shippingContactPerson,
        shippingContactPhone,
        plateNumber,
        shipmentStatus,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        isSubmit,
      } = newVal;

      Object.assign(formData, {
        id,
        orderNo,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        asnCode,
        partnerId,
        partnerCode,
        partnerName,
        asnDate,
        arriveDate,
        modeTransport,
        trackingNumber,
        storageLocationId,
        storageLocationCode,
        storageLocationName,
        carrier,
        shippingContactPerson,
        shippingContactPhone,
        plateNumber,
        shipmentStatus,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        isSubmit,
        details: [details], // 使用可选的 details 对象
      });

      // 检查 details 是否有效再进行赋值
      if (newVal.id) {
        formData.details[0].qualityExceptionId = newVal.id;
        getD1(formData.details[0].qualityExceptionId);
        console.log(formData.details[0].qualityExceptionId);
      }
    }
  }
);
/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  orderNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  asnCode: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  asnDate: "",
  arriveDate: "",
  modeTransport: "",
  trackingNumber: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  carrier: "",
  shippingContactPerson: "",
  shippingContactPhone: "",
  plateNumber: "",
  shipmentStatus: "3",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  isSubmit: 1,
  details: [
    {
      id: "",
      qualityExceptionId: "",
      qualityExceptionCode: "",
      teamUserName: "",
      teamUserId: "",
      isLeader: "",
      departmentName: "",
      departmentId: "",
      roleName: "",
      telNumber: "",
      isSubmit: 1,
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  asnCode: [{ required: true, message: "请输入送货单号", trigger: "blur" }],
  orderNo: [{ required: true, message: "请输入订单编号", trigger: "blur" }],
  organizationId: [
    { required: true, message: "请输入公司ID;基本信息", trigger: "blur" },
  ],
  organizationCode: [
    { required: true, message: "请输入公司代码;基本信息", trigger: "blur" },
  ],
  organizationName: [
    { required: true, message: "请输入公司名称;基本信息", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  plantCode: [{ required: true, message: "请输入工厂代码", trigger: "blur" }],
  plantName: [{ required: true, message: "请输入工厂名称", trigger: "blur" }],
  partnerId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  partnerCode: [
    { required: true, message: "请输入供应商编号", trigger: "blur" },
  ],
  partnerName: [
    { required: true, message: "请输入供应商名称", trigger: "blur" },
  ],
  asnDate: [{ required: true, message: "请输入送货日期", trigger: "blur" }],
  arriveDate: [
    { required: true, message: "请输入预计到货日期", trigger: "blur" },
  ],

  shipmentStatus: [
    { required: true, message: "请输入发货状态", trigger: "change" },
  ],

  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  createdUserId: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  createdUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  lastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  lastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  deleted: [{ required: true, message: "请输入是否删除", trigger: "blur" }],
  sonasnId: [{ required: true, message: "请输入ASN单ID", trigger: "blur" }],
  sonorderId: [{ required: true, message: "请输入订单ID", trigger: "blur" }],
  sonmaterialDetailId: [
    { required: true, message: "请输入ASN关联的物料信息表ID", trigger: "blur" },
  ],
  sonunitBarcode: [
    { required: true, message: "请输入箱标签号", trigger: "blur" },
  ],
  sonmaterialId: [{ required: true, message: "请输入物料id", trigger: "blur" }],
  sonmaterialCode: [
    { required: true, message: "请选择物料", trigger: "change" },
  ],
  sonmaterialName: [
    { required: true, message: "请输入物料名称", trigger: "blur" },
  ],
  sonsupplyBatch: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
  ],
  sonpackingUnitQuantity: [
    { required: true, message: "请输入包装容量", trigger: "blur" },
    { validator: quantity, trigger: "change" },
  ],
  sonquantity: [
    { required: true, message: "请输入包装数量", trigger: "blur" },
    { validator: quantity, trigger: "change" },
  ],
  sonisreceive: [
    { required: true, message: "请输入是否收货", trigger: "blur" },
  ],
  sonunitCode: [
    { required: true, message: "请输入数量单位", trigger: "change" },
  ],

  soncreateTime: [
    { required: true, message: "请输入创建时间", trigger: "blur" },
  ],
  soncreatedUserId: [
    { required: true, message: "请输入创建人", trigger: "blur" },
  ],
  soncreatedUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  sonlastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  sonlastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  sonlastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  sondeleted: [{ required: true, message: "请输入是否删除", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  formRef.value.clearValidate();
};

const details = {
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  teamUserName: "",
  teamUserId: "",
  isLeader: "",
  departmentName: "",
  departmentId: "",
  roleName: "",
  telNumber: "",
  isSubmit: 1,
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = {}; // 创建一个空对象
  formData.details.push(sondata);
};

watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.qualityExceptionId = "";
  formData.qualityExceptionCode = "";
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.orderNo = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.asnCode = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.asnDate = "";
  formData.arriveDate = "";
  formData.modeTransport = "";
  formData.trackingNumber = "";
  formData.storageLocationId = "";
  formData.storageLocationCode = "";
  formData.storageLocationName = "";
  formData.carrier = "";
  formData.shippingContactPerson = "";
  formData.shippingContactPhone = "";
  formData.plateNumber = "";
  formData.shipmentStatus = "3";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.isSubmit = 1;
}

const loading = ref(false);

/** ASN单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/q8dd1/save",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
function handleone(index: any) {
  formRef.value.validate(async (valid: any) => {
    formData.details[index].qualityExceptionId =
      formData.details[0].qualityExceptionId;
    if (valid) {
      loading.value = true;
      await request({
        url: "/qms/q8dd1/saveone",
        method: "post",
        data: formData.details[index],
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
function quantity(rule, value, callback) {
  if (value < 1) {
    callback(new Error("包装容量必须大于等于1"));
  } else {
    callback();
  }
}
// 获取当前用户信息
const getUser = async () => {
  const res = await getUserInfo();
  formData.grantPersonId = res.data.userId;
  formData.grantPersonName = res.data.userName;
};
/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, row, index: number) {
  formData.receivePersonId = "";
  formData.receivePersonName = "";
  formData.receiveDepartmentId = ids;
  personList.value = [];
  changeDept(ids);
  console.log(ids);
  row.departmentId = ids;
  console.log(row.departmentId);
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, row, index: number) {
  formData.receiveDepartmentName = datas.organizationName
    ? datas.organizationName
    : "";
  console.log(datas.organizationName);
  row.departmentName = datas.organizationName;
  console.log(row.departmentName);
}

const dataObject = (item: string, index: number) => {
  return {
    name: item == "领用部门" ? "领用部门" : "使用部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const changeDept = async (id) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });

    personList.value = res.data;
    personList.value.map((item: any) => {
      item.label = `${item.firstName}`;
      item.value = `${item.id}`;
    });
  }
};

// 人员改变时
const changePerson = (e: any, name: string, row) => {
  if (e) {
    if (name == "领用人") {
      personList.value.forEach((item: any) => {
        if (item.id == e) {
          formData.receivePersonName = item.firstName;
          row.teamUserName = item.firstName;
          row.teamUserId = item.id;
        }
      });
    }
  } else {
    formData.receivePersonId = "";
    formData.receivePersonName = "";
  }
};

//过去业务信息D71
const getD1 = async (id: string) => {
  const res = await request({
    url: "/qms/q8dd1/getD1",
    method: "post",
    data: {
      qualityExceptionId: id,
    },
  });
  if (res.data != null) {
    Object.assign(formData.details, res.data);
    //formData.details = res.data;
  } else {
    formData.id = "";
  }
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 50vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
